import {xor} from 'lodash'
export const tableMixins = {
  data: () => ({
    pageNum: 1,
    rowsNum: 10,
    total: 0,
    selectedRowKeys: [],
    selectedRows: []
  }),
  computed: {
    customRow() {
      return data => ({
        on: {
          click: () => {
            this.transferData(data)
          }
        }
      })
    },
    rowSelection() {
      return {
        type: this.checkboxType || 'checkbox',
        selectedRowKeys: this.selectedRowKeys,
        onChange: selectedRowKeys => {
          const keyList = xor(this.selectedRowKeys, selectedRowKeys)
          keyList.map(e => {
            this.transferData(this.data.find(item => item.id === e) || {})
          })
          this.selectedRowKeys = selectedRowKeys
        }
      }
    },
    pagination() {
      return {
        total: this.total,
        current: this.pageNum,
        pageSize: this.rowsNum,
        showTotal: total => `共${total}条记录，第${this.pageNum} / ${Math.ceil(total / this.rowsNum)} 页`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: this.pageSizeOptions,
        onChange: this.pageChange,
        onShowSizeChange: this.sizeChange
      }
    }
  },
  methods: {
    pageChange(pageNum) {
      this.pageNum  = pageNum
      this.getData()
    },
    sizeChange(pageNum, pageSize) {
      this.pageNum  = 1
      this.rowsNum = pageSize
      this.getData()
    },
    transferData(record) {
      const keyIndex = this.selectedRowKeys.findIndex(e => e === record.id)
      if (keyIndex === -1) {
        this.selectedRowKeys.push(record.id)
        this.selectedRows.push({ ...record })
        return false
      } else {
        const rowIndex = this.selectedRows.findIndex(e => e.id === record.id)
        this.selectedRowKeys.splice(keyIndex, 1)
        this.selectedRows.splice(rowIndex, 1)
      }
    }
  }
}
